package com.github.maojx0630.easy.translate.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

/**
 * @author 毛家兴
 * @since 2024-02-06 09:01
 */
@Slf4j
@ConditionalOnMissingBean({ObjectToJsonObject.class,ObjectMapper.class})
public class FastJsonMissObjectMapperConfiguration {

  @Bean
  @ConditionalOnMissingBean(ObjectToJsonObject.class)
  @ConditionalOnClass(com.alibaba.fastjson2.JSONObject.class)
  public ObjectToJsonObject fastJson2() {
    return o -> {
      String jsonString;
      try {
        jsonString=com.alibaba.fastjson2.JSON.toJSONString(o);
      } catch (Exception e) {
        log.error("json解析失败" + e.getMessage(), e);
        return null;
      }
      try {
        return com.alibaba.fastjson2.JSONObject.parseObject(jsonString);
      } catch (ClassCastException e) {
        log.error("json解析失败" + e.getMessage(), e);
        return null;
      }
    };
  }

  @Bean
  @ConditionalOnMissingBean(ObjectToJsonObject.class)
  @ConditionalOnClass(com.alibaba.fastjson.JSONObject.class)
  public ObjectToJsonObject fastJson() {
    return o -> {
      String jsonString;
      try {
        jsonString=com.alibaba.fastjson.JSON.toJSONString(o);
      } catch (Exception e) {
        log.error("json解析失败" + e.getMessage(), e);
        return null;
      }
      try {
        return com.alibaba.fastjson.JSONObject.parseObject(jsonString);
      } catch (ClassCastException e) {
        log.error("json解析失败" + e.getMessage(), e);
        return null;
      }
    };
  }


}
